#include <Arduino.h>
#include <Wire.h>
#include "serial.h"
#include "oled.h"

// 存储所有信息
String current_date = "2023-01-01";
String current_time = "00:00:00";
String current_city = "未知";
String current_weather = "未知";
String current_temp = "0";

String medicine_name = "中药"; // 默认药品名称
int min_temp = 5;             // 药品最低存储温度
int max_temp = 25;            // 药品最高存储温度
bool temp_warning = false;    // 温度警告标志

// 滚动显示参数
unsigned long scrollMillis = 0;
const long scrollInterval = 3000; // 3秒切换一次屏幕
int currentScreen = 0; // 0:第一屏，1:第二屏

// 内部定时器变量（自动走时）
unsigned long previousMillis = 0;
const long interval = 1000;
int hours, minutes, seconds;

void showScreen0() { // 第一屏：时间、城市
    u8g2.clearBuffer();
    u8g2.setCursor(0, 16);
    u8g2.print(current_date + " " + current_time); // 日期+时间
    u8g2.setCursor(0, 35);
    u8g2.print("城市: " + current_city); // 城市
    u8g2.sendBuffer();
}

void showScreen1() { // 第二屏：天气、温度、药品状态
    u8g2.clearBuffer();
    u8g2.setCursor(0, 16);
    u8g2.print("天气: " + current_weather); // 天气
    u8g2.setCursor(0, 35);
    u8g2.print("温度: " + current_temp + "°C"); // 温度
    
    // 新增药品温度检查
    int current_temp_int = current_temp.toInt();
    if (current_temp_int < min_temp || current_temp_int > max_temp) {
        temp_warning = true;
        u8g2.setCursor(0, 55);
        u8g2.print("警告: " + medicine_name + "可能损坏!");
    } else {
        temp_warning = false;
        u8g2.setCursor(0, 55);
        u8g2.print(medicine_name + "储存正常");
    }
    
    u8g2.sendBuffer();
}

void showAllInfo() {
    if (currentScreen == 0) showScreen0();
    else showScreen1();
}

// 解析串口数据
void parseSerialData(String data) {
    // 数据格式: 日期时间,城市,天气,温度[,药品名,最低温,最高温]
    int comma1 = data.indexOf(',');
    int comma2 = data.indexOf(',', comma1 + 1);
    int comma3 = data.indexOf(',', comma2 + 1);
    int comma4 = data.indexOf(',', comma3 + 1);
    int comma5 = data.indexOf(',', comma4 + 1);
    int comma6 = data.indexOf(',', comma5 + 1);

    if (comma1 > 0 && comma2 > 0 && comma3 > 0) {
        // 解析基本天气信息
        String datetime_str = data.substring(0, comma1);
        current_date = datetime_str.substring(0, 10);
        current_time = datetime_str.substring(11);
        
        // 解析时分秒
        int colon1 = current_time.indexOf(':');
        int colon2 = current_time.indexOf(':', colon1 + 1);
        hours = current_time.substring(0, colon1).toInt();
        minutes = current_time.substring(colon1 + 1, colon2).toInt();
        seconds = current_time.substring(colon2 + 1).toInt();
        
        current_city = data.substring(comma1 + 1, comma2);
        current_weather = data.substring(comma2 + 1, comma3);
        current_temp = data.substring(comma3 + 1, comma4 > 0 ? comma4 : data.length());
        
        // 如果有药品参数则解析
        if (comma4 > 0 && comma5 > 0 && comma6 > 0) {
            medicine_name = data.substring(comma4 + 1, comma5);
            min_temp = data.substring(comma5 + 1, comma6).toInt();
            max_temp = data.substring(comma6 + 1).toInt();
        }
        
        showAllInfo(); // 刷新当前屏幕
    }
}

void setup() {
    Serial.begin(115200);
    oledInit();
    oledShow(0, 16, "初始化中...");
    delay(1000);
    
    // 初始化时间和定时器
    hours = 0;
    minutes = 0;
    seconds = 0;
    previousMillis = millis();
    scrollMillis = millis();
}

void loop() {
    // ================== 自动走时 ==================
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        seconds++;
        if (seconds >= 60) { 
            seconds = 0;
            minutes++;
            if (minutes >= 60) {
                minutes = 0;
                hours++;
                if (hours >= 24) hours = 0; // 补全时间进位逻辑
            }
        }
        // 补全前导零（如09:05:03）
        current_time = String(hours < 10 ? "0" + String(hours) : String(hours)) + ":" +
                       String(minutes < 10 ? "0" + String(minutes) : String(minutes)) + ":" +
                       String(seconds < 10 ? "0" + String(seconds) : String(seconds));
        showAllInfo(); // 刷新时间
    }

    // ================== 屏幕滚动 ==================
    if (currentMillis - scrollMillis >= scrollInterval) {
        scrollMillis = currentMillis;
        currentScreen = (currentScreen + 1) % 2; // 0 ↔ 1 循环切换
        showAllInfo(); // 切换显示内容
    }

    // ================== 接收串口数据 ==================
    if (Serial.available()) {
        String data = Serial.readStringUntil('\n');
        data.trim();
        parseSerialData(data);
        scrollMillis = currentMillis; // 收到新数据后重置滚动计时
    }
}